package com.fulihui.usercore.biz.conv;

import com.fulihui.usercore.dal.dataobj.CustomerDO;
import com.fulihui.usercore.dto.CustomerDTO;
import org.near.toolkit.common.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.fulihui.usercore.common.util.DataSafe.aesEncrypt;
import static com.fulihui.usercore.common.util.DataSafe.autoDecrypt;

/**
 * 客户信息装换工具类，用 Spring 管理单例模式
 *
 * @author Willard.Hu on 2016/11/9 0009.
 */
@Component
public class CustomerConv {
    /**
     * 数据加密的 AES KEY
     */
    @Value("${data.safe.aeskey}")
    private String dataSafeAesKey;

    public String getDataSafeAesKey() {
        return dataSafeAesKey;
    }

    public CustomerDO toDO(CustomerDTO dto) {
        // TODO 目前只有手机号，当其他信息也录入时需要保密处理
        CustomerDO customerDO = new CustomerDO();
        customerDO.setCustomerId(dto.getCustomerId());
        customerDO.setName(dto.getName());
        customerDO.setAge(dto.getAge());
        customerDO.setGender(dto.getGender());
        customerDO.setProfessional(dto.getProfessional());
        customerDO.setCardType(dto.getCardType());
        customerDO.setCardno(dto.getCardno());
        if (StringUtil.isNotBlank(dto.getMobileNo())) {
            customerDO.setMobileNo(aesEncrypt(dto.getMobileNo(), dataSafeAesKey));
        }
        customerDO.setGmtCreate(dto.gmtCreate());
        customerDO.setGmtModified(dto.gmtModified());
        return customerDO;
    }

    public CustomerDTO toDTO(CustomerDO customerDO) {
        // TODO 目前只有手机号，当其他信息也录入时需要保密处理
        CustomerDTO dto = new CustomerDTO();
        dto.setCustomerId(customerDO.getCustomerId());
        dto.setName(customerDO.getName());
        dto.setAge(customerDO.getAge());
        dto.setGender(customerDO.getGender());
        dto.setProfessional(customerDO.getProfessional());
        dto.setCardType(customerDO.getCardType());
        dto.setCardno(customerDO.getCardno());
        if (StringUtil.isNotBlank(customerDO.getMobileNo())) {
            dto.setMobileNo(autoDecrypt(customerDO.getMobileNo()));
        }
        dto.gmtCreate(customerDO.getGmtCreate());
        dto.gmtModified(customerDO.getGmtModified());
        return dto;
    }

    public List<CustomerDTO> toList(List<CustomerDO> dataObjs) {
        if (CollectionUtils.isEmpty(dataObjs)) {
            return Collections.emptyList();
        }
        return dataObjs.stream().map(this::toDTO).collect(Collectors.toList());
    }
}
